package com.sora.controller;

import com.sora.enums.ResultCode;
import com.sora.exception.ApiException;
import com.sora.model.vo.ResultVO;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice
public class ExceptionControllerAdvice {

    @ExceptionHandler(ApiException.class)
    public ResultVO<String> apiExceptionHandler(ApiException e) {
        return new ResultVO<>(e.getResultCode(), e.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO<List> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<String> list = new ArrayList<>();
        for (ObjectError error : e.getBindingResult().getAllErrors()) {
            list.add(error.getDefaultMessage());
        }
        return new ResultVO<>(ResultCode.VALIDATE_FAILED, list);
    }
}
